//
//  WKWebViewController.m
//  CaiJinSuo2.0
//
//  Created by 张琦 on 16/9/16.
//  Copyright © 2016年 张琦. All rights reserved.
//

#import "WKWebViewController.h"
#import <WebKit/WebKit.h>
#import <objc/runtime.h>
NSString *const progressColorKey = @"progressColorKey";

@interface WKWebViewController ()<WKNavigationDelegate>
@property (strong, nonatomic) CALayer *progresslayer;
@property (nonatomic, strong) UIView *viewFaild;
@property (nonatomic, strong) UIImageView *imgViewAlert;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIButton *btn;
@property (nonatomic, strong) UIButton *btnClose;

@end

@implementation WKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"加载中...";
    
    WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64)];
    webView.navigationDelegate = self;
    //添加观察者,观察wkwebview的estimatedProgress属性
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:webView];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    self.webView =webView;
    [self initWithDefault];
    [self initWithProgressView];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"返回" forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 40, 45);
    UIButton *btnClose = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnClose setTitle:@"关闭" forState:UIControlStateNormal];
    btnClose.frame = CGRectMake(45, 0, 40, 45);

    [btn addTarget:self action:@selector(handleBtn) forControlEvents:UIControlEventTouchUpInside];
    [btnClose addTarget:self action:@selector(handleBtnClose) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:btn], [[UIBarButtonItem alloc] initWithCustomView:btnClose]];
    btnClose.hidden = YES;
    self.btn = btn;
    self.btnClose = btnClose;
}



- (void)handleBtn {
    if (self.webView.canGoBack) {
        [self.webView goBack];
    } else {
        [TabBarView_Manager popViewControllerAnimated:YES];
    }
}

- (void)handleBtnClose {
    [TabBarView_Manager popViewControllerAnimated:YES];

}

//- (UIView *)viewFaild {
//    if (!_viewFaild) {
//        self.viewFaild = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64)];
//        [self.view addSubview:self.viewFaild];
//        self.imgViewAlert = [[UIImageView alloc] init];
//        [self.viewFaild addSubview:self.imgViewAlert];
//        self.imgViewAlert.image = [UIImage imageNamed:@"xiaotuan"];
//        CGSize size = self.imgViewAlert.image.size;
//        [self.imgViewAlert mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerX.mas_equalTo(self.viewFaild.mas_centerX);
//            make.centerY.mas_equalTo(self.viewFaild.mas_centerY);
//            make.width.mas_equalTo(size.width);
//            make.height.mas_equalTo(size.height);
//        }];
//    }
//    return _viewFaild;
//}


- (void)initWithDefault{
    self.progressColor = [UIColor colorWithRed:22.f / 255.f green:126.f / 255.f blue:251.f / 255.f alpha:.8];;
}

- (void)initWithProgressView{
    UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 3)];
    progress.backgroundColor = [UIColor clearColor];
    [self.view addSubview:progress];
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, 3);
    layer.backgroundColor = self.progressColor.CGColor;
    [progress.layer addSublayer:layer];
    self.progresslayer = layer;
}

- (UIColor *)progressColor{
    return objc_getAssociatedObject(self, &progressColorKey);
}

- (void)setProgressColor:(UIColor *)progressColor{
    objc_setAssociatedObject(self, &progressColorKey, progressColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self initWithProgressView];
}


- (void)dealloc{
//    [(WKWebView *)self removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    self.title = webView.title;
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.title = webView.title;
    if (self.webView.canGoBack) {
        self.btnClose.hidden = NO;
    } else {
        self.btnClose.hidden = YES;
    }

}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
//    self.viewFaild.hidden = NO;
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progresslayer.opacity = 1;
        //不要让进度条倒着走...有时候goback会出现这种情况
        if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) {
            return;
        }
        self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);
        if ([change[@"new"] floatValue] == 1) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
            });
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
